<?php
namespace cms\modules\v1\models\coin;

use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\Status;
use common\services\upload\Qiniu;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class User
 * @package cms\modules\v1\models
 */
class CoinRechargeSetting extends \common\models\coin\CoinRechargeSetting
{

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            [['name','money','coin'], 'required','message' => '{attribute}不能为空','on' => 'addEdit'],

        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'name' => '名称',
            'coin' => '金币',
            'money' => '价格',
            'ios_id' => '苹果内购',

        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'addEdit' => [
                'name',
                'coin',
                'money',
                'ios_id',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件

            //得到文章的总数
            $count = self::getCountByAndWhere($searchWhere['where'], $searchWhere['andWhere']);
            $data = static::setPageinationAPI($page, $size, $count);

            //设置分页
            $offset = ($data['page'] - 1) * $size;

            //排序 order
            $orderSql = 'id ASC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
        $status = Yii::$app->request->get('status','');

        if ($status) {
            $where['status'] = (int) $status;
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with()->asArray()->all();
        foreach($list as $key => &$value) {
            $value['money'] = (float) $value['money'] ?: '0';
            $value['coin'] = (float) $value['coin'] ?: '0';
            $value['time'] =  $value['update_time'] ?: $value['create_time'];
        }
        return $list;
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $post = Yii::$app->request->post();
            $id = isset($post['id']) && !empty($post['id']) ? intval($post['id']) : 0;
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));


            if (!empty($id)) {
                //更新操作
                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥~~');
                }
            } else {
                //添加操作
                $data['update_time'] = $data['create_time'] = date('Y-m-d H:i:s');
                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥~~');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            $id = (int) $id;

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $info = static::getOneInfoById($id);
            if(empty($info)) {
                throw new Exception('信息不存在');
            }

            $info['money'] = floatval($info['money']);
            $info['coin'] = floatval($info['coin']);
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 启用禁用 等切换装填
     * @return array
     */
    public function setField()
    {
        try {
            $isDelete = Yii::$app->request->post('is_delete','');
            $status = Yii::$app->request->post('status','');
            $listOrder = Yii::$app->request->post('list_order','');
            $id = Yii::$app->request->post('id',0);
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            if ($status) {
                $data['status'] = (int) $status;
            }

            if ($isDelete) {
                $data['is_delete'] = (int) $isDelete;
            }

            if ($listOrder) {
                $data['list_order'] = (int) $listOrder;
            }


            $data['update_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('操作失败');
            }
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取map信息
     * @return array
     */
    public function getSelectMap() {
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
        $result = static::getFormArray($where,'id','name');
        return Functions::formatRestAPI(0, '', $result);
    }

}
